define([
    'app',
    'fuzzysearch',
    'zTree-exhide'
], function(app, fuzzySearch) {
    app.controller('searchFile', function($http, $timeout, $uibModalInstance, _context) {
        var self = this;

        self.selectedFile = null;

        self.init = function() {
            $http.get('/note/data/tree').then(function(response) {
                if (response.status == 200) {
                    var treeNodes = response.data || [];
                    _.each(treeNodes, function(node) {
                        if (node.module) {
                            node.iconSkin = 'module';
                        }
                    });
                    $.fn.zTree.init($('#file-tree'), {
                        view: {
                            showTitle: false
                        },
                        callback: {
                            onClick: function(event, treeId, treeNode) {
                                $timeout(function() {
                                    if (treeNode && treeNode.file) {
                                        self.selectedFile = getFileNode(treeNode);
                                    } else {
                                        self.selectedFile = null;
                                    }
                                });
                            },
                            onDblClick: function(event, treeId, treeNode) {
                                if (treeNode && treeNode.file) {
                                    $uibModalInstance.close(getFileNode(treeNode));
                                }
                            }
                        }
                    }, treeNodes);
                    //
                    fuzzySearch('file-tree', '#file-filter', true, true);
                    $('#file-filter').change(function() {
                        $timeout(function() {
                            self.selectedFile = null;
                        });
                    });
                    if (_context) {
                        $('#file-filter').val(_context).trigger('propertychange');
                    }
                }
            });
        }

        function getFileNode(node) {
            var file = {};
            file.name = node.oldname || node.name;
            file.path = _.map(node.getPath(), function(_node) {
                return _node.oldname || _node.name;
            }).join('/');
            return file;
        }

        self.openFile = function() {
            if (self.selectedFile) {
                $uibModalInstance.close(self.selectedFile);
            }
        }

        self.close = function() {
            $uibModalInstance.close();
        }
    });
});
